/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proyectoia;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;

/**
 *
 * @author Brian
 */
public class Plotter extends ApplicationFrame implements Runnable  {
    
    private LinkedBlockingDeque dynamicDataBuffe;
    private Data finalData;
    private ArrayList<Data> dataBuffer;
    XYSeries serverSeries[];
    int numServers;
    //XYSeries maxTimeServer;

    public Plotter(ArrayList<Data> dataBuffer) {
        super("...");
        this.dataBuffer = dataBuffer;
    }

    public Plotter (LinkedBlockingDeque buffer, int numServers) {
        super("Temps màxim de transmisió");
        this.dynamicDataBuffe = buffer;  
        this.numServers = numServers;
        
        XYSeriesCollection data = new XYSeriesCollection();  
        
        serverSeries = new XYSeries[numServers];
        for (int i = 0; i < numServers; i++) {
            serverSeries[i] = new XYSeries("Servidor "+i);
            data.addSeries(serverSeries[i]);
        }
        
        
        XYItemRenderer renderer = new StandardXYItemRenderer();
        NumberAxis rangeAxis = new NumberAxis("Temps (ms)");
        rangeAxis.setAutoRangeIncludesZero(false);
        XYPlot subplot = new XYPlot(data, null, rangeAxis, renderer);
        subplot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);

        // parent plot...
        CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new NumberAxis("Operacions"));
        plot.setGap(10.0);
        
        // add the subplots...
//        plot.add(subplot1, 1);
        plot.add(subplot, 1);
        plot.setOrientation(PlotOrientation.VERTICAL);
        // return a new chart containing the overlaid plot...
        JFreeChart chart =  new JFreeChart("Temps màxim de transmisió",
                              JFreeChart.DEFAULT_TITLE_FONT, plot, false);
        
        ChartPanel panel = new ChartPanel(chart, true, true, true, false, true);
        panel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(panel);
    }
 

    @Override
    public void run() { 
        for (int i = 0; true; i++) {
            try {               
                Data element = (Data) dynamicDataBuffe.takeFirst();
                finalData = element;
                for (int j = 0; j < numServers; j++) {
                serverSeries[j].add(i, element.getTime(j));
                }
                
            } catch (InterruptedException ex) {
                Logger.getLogger(Plotter.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }

    }
     
    
    public void compareServersTime(String filename, int w, int h) {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int i = 0; i < dataBuffer.get(0).getNumServers(); i++) {
           
            dataset.addValue(finalData.getNumRequest(i), "Servidor", Integer.toString(i));
        }
        JFreeChart chart = ChartFactory.createBarChart("Número de peticiones por servidor",
                                                       "Servidores", 
                                                       "Número de peticiones", 
                                                       dataset, 
                                                       PlotOrientation.VERTICAL,
                                                       false, 
                                                       false, 
                                                       false);
       
      
        
        try {
            ChartUtilities.saveChartAsJPEG(new File("charts/"+filename+".jpg"), chart, w, h);
        } catch (IOException e) {
            System.err.println("Problem occurred creating chart. "+e.getMessage());

        }
        
    }
    
    
    public void compareExecutionsTime(ArrayList<Data> dataList, ArrayList<String> tags, String filename, int w, int h) {
         DefaultCategoryDataset dataset = new DefaultCategoryDataset();
         int i = 0;
         for (Data data : dataList) {
             double execTime = (double)data.executionTime/1000.0;
             double transTime = data.getTime(i)/1000.0;
             
             dataset.addValue(execTime,
                              "TiempoEjecucion",
                              tags.get(i));
             dataset.addValue(transTime,
                              "TiempoTranmision",
                              tags.get(i));          
            i++;

         }
         
          JFreeChart chart = ChartFactory.createBarChart("Tiempo de ejecución",
                                                       "Operadores", 
                                                       "Tiempo (ms)", 
                                                       dataset, 
                                                       PlotOrientation.VERTICAL,
                                                       false, 
                                                       false, 
                                                       false);
       
      
        
        try {
            ChartUtilities.saveChartAsJPEG(new File("charts/"+filename+".jpg"), chart, w, h);
        } catch (IOException e) {
            System.err.println("Problem occurred creating chart. "+e.getMessage());

        }
    }
}
